import React, { Component } from 'react';
import Particles from 'react-particles-js';
import './login.scss';
import 'antd/dist/antd.css';

import { FormInstance } from 'antd/lib/form';

import { Form, Input, Button, Checkbox, notification as Notification } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { login } from '../../api/login';

class Login extends Component {
  state = { clientHeight: document.documentElement.clientHeight || document.body.clientHeight };
  formRef = React.createRef(FormInstance);

  constructor(props) {
    super(props);
    this.onResize = this.onResize.bind(this);

    const item = localStorage.getItem('user');
    if (item) {
      this.jumpMainPage(JSON.parse(item));
    }
  }

  componentDidMount() {
    window.addEventListener('resize', this.onResize);
  }

  componentWillUnmount() {
    window.addEventListener('resize', this.onResize);
    // componentWillMount进行异步操作时且在callback中进行了setState操作时，需要在组件卸载时清除state
    this.setState = () => null;
  }

  onResize() {
    this.setState({ clientHeight: document.documentElement.clientHeight || document.body.clientHeight });
  }

  jumpMainPage = (user) => {
    const { manager } = user;
    if (manager) {
      this.props.history.push('/admin/user/list');
    } else {
      this.props.history.push('/user');
    }
  };

  render() {
    const onFinish = (values) => {
      console.log('Received values of form: ', values);
    };
    const onLogin = (e) => {
      this.formRef.current.validateFields().then((values) => {
        console.log(values, typeof values, 'values');
        const { username, password } = values;
        login(username, password).then(({ data }) => {
          localStorage.setItem('user', JSON.stringify(data));
          this.jumpMainPage(data);
        }).catch((e) => {
          console.log(e, typeof e, 'e');
        });
      }).catch((errorInfo) => {

        /*
        errorInfo:
        {
          values: {
            username: 'username',
            password: 'password',
          },
          errorFields: [
            { password: ['username'], errors: ['Please input your Password!'] },
          ],
          outOfDate: false,
        }
        */
        const { errorFields } = errorInfo;
        Notification.error({
          message: errorFields[0].errors[0],
          duration: 2
          // description: errorFields[0].errors[0]
        });
      });
      e.preventDefault();
    };
    return (
      <div className="container">
        <Particles
          height={this.state.clientHeight - 5 + 'px'}
          params={{
            number: { value: 50 },
            ize: { value: 3 },
            interactivity: {
              events: {
                onhover: { enable: true, mode: 'repulse' }
              }
            }
          }}
        />

        <div className="content">
          <div className="title">用户登录</div>
          <Form
            ref={this.formRef}
            initialValues={{ remember: true, username: '151164412', password: '123456' }}
            onFinish={onFinish}
            className="login-form"
          >
            <Form.Item
              name="username"
              rules={[{ required: true, message: '请填写用户名！' }]}
            >
              <Input
                prefix={<UserOutlined twoToneColor='rgba(0,0,0,.25)'/>}
                placeholder="用户名"/>
            </Form.Item>

            <Form.Item
              name="password"
              rules={[{ required: true, message: '请填写密码！' }]}
            >
              <Input.Password
                prefix={<LockOutlined twoToneColor='rgba(0,0,0,.25)'/>}
                autoComplete="true"
                placeholder="密码"/>
            </Form.Item>
            <Form.Item>
              <Form.Item name="remember" valuePropName="checked" noStyle>
                <Checkbox className="white-font">记住我</Checkbox>
              </Form.Item>

              <a className="login-form-forgot" href="/#">忘记密码</a>
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit" block onClick={onLogin}>
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    );
  }
}

export default Login;
